﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pavilion.GameTools;
using System.Xml.Linq;

namespace Pavilion.Locks
{
    class ConnectionActionRequestLock : ILock
    {
        public ConnectionAction ConnectionAction { get; set; }
        public string GameItemName { get; set; }

        public ILock Clone()
        {
            return new ConnectionActionRequestLock()
            {
                GameItemName = this.GameItemName,
                ConnectionAction = this.ConnectionAction
            };
        }

        public void Deserialize(XElement lockElement, string resourceName)
        {
            ConnectionAction = GameEngine.ParseObject<ConnectionAction>(lockElement.Attribute("ConnectionAction").Value);
        }

        public XElement Serialize()
        {
            XElement lockElement = new XElement("Lock");

            lockElement.Add(new XAttribute("ConnectionAction", ConnectionAction));

            return lockElement;
        }

        public LockMonitorBase CreateLockMonitor(GameItem gameItem)
        {
            ConnectionTool connectionTool = gameItem.ObtainTool<ConnectionTool>();
            return new ConnectionActionRequestLockMonitor(this);
        }

        public override string ToString()
        {
            return this.GetType().Name;
        }

        private class ConnectionActionRequestLockMonitor : LockMonitorBase
        {
            public override ILock Lock { get { return connectionLock; } }
            private ConnectionTool connectionTool;
            private ConnectionActionRequestLock connectionLock;

            public ConnectionActionRequestLockMonitor(ConnectionActionRequestLock connectionLock)
            {
                this.connectionLock = connectionLock;
            }

            public override void Dispose()
            {
                this.connectionLock = null;
                this.connectionTool.ActionRequested -= new Action<ConnectionAction>(ConnectionTool_ActionRequested);
                this.connectionTool = null;
            }

            public override void Load(GameItem gameItem)
            {
                this.connectionTool = gameItem.ObtainTool<ConnectionTool>();
                this.connectionTool.ActionRequested += new Action<ConnectionAction>(ConnectionTool_ActionRequested);
            }

            public override void UpdateLock() { }

            private void ConnectionTool_ActionRequested(ConnectionAction action)
            {
                IsOpen = (action == connectionLock.ConnectionAction);
                IsOpen = false;
            }
        }
    }
}
